<template>
  <div class="logisticsBill_block">
    <div class="top">
      <search-bar
        v-model="searchModel"
        :search-data="searchData"
        :config="searchData"
        style="margin-top: 0; margin-left: -20px; padding-top: 0.2rem"
        @search="handleSearchSubmit"
        @searchReset="handleSearchReset"
      />
    </div>

    <div class="bottom">
      <div class="btn_area" size="medium">
        <el-button type="" size="medium" style="margin-left: 0.1rem" @click="addCustomer">导出</el-button>
      </div>
      <LPTablePage
        ref="tablePage"
        :show-index="true"
        :table-data="tableData"
        :table-column="tableColumn"
        :total="total"
        :current-page="currentPage"
        :selection="false"
        :selectable="selectable"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
        @handleSelectionChange="handleSelectionChange"
      >
        <template slot="logisticsNumber" slot-scope="{ row }">
          <span style="color: #3274f6; cursor: pointer" @click="navigateToDetail(row.id, 'logisticsNumber')">
            {{ row.logisticsNumber }}
          </span>
        </template>
        <template slot="taskNumber" slot-scope="{ row }">
          <span style="color: #3274f6; cursor: pointer" @click="navigateToDetail(row.id, 'taskNumber')">
            {{ row.taskNumber }}
          </span>
        </template>
        <template slot="documentStatus" slot-scope="{ row }">
          <span>
            <template v-if="row.documentStatus == 1"><span class="status-dot orange" />待派车</template>
            <template v-else-if="row.documentStatus == 2"><span class="status-dot blue" />全部派车</template>
            <template v-else-if="row.documentStatus == 3"><span class="status-dot green" />已完成</template>
            <template v-else-if="row.documentStatus == 4"><span class="status-dot gray" />已取消</template>
            <!-- <template v-else-if="row.documentStatus == 5"><span class="status-dot red" />已驳回</template> -->
            <template v-else>未知状态</template>
          </span>
        </template>
      </LPTablePage>
    </div>
    <!-- 编辑or新增 -->
    <base-dialog
      :visible="addVisile"
      :title="(isEdit ? '编辑' : '新增') + '物流公司'"
      width="918px"
      class="addDictDialog"
      @handleDialogSubmit="handleAddSubmit"
      @handleDialogCancle="handleAddCancle"
    >
      <el-form
        ref="dictForm"
        :model="dictModel"
        :rules="dictRule"
        label-width="120px"
        class="dictForm"
        label-position="top"
        size="medium"
      >
        <el-row :gutter="50">
          <el-col :span="12">
            <el-form-item label="物流公司名称:" prop="dictValue">
              <el-input v-model.trim="dictModel.dictValue" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物流公司编号:" prop="dictValue">
              <el-input v-model.trim="dictModel.dictValue" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="统一社会信用代码:" prop="remark">
              <el-input v-model="dictModel.remark" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法人:" prop="remark">
              <el-input v-model="dictModel.remark" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在区域:" prop="remark">
              <el-input v-model="dictModel.remark" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址:" prop="remark">
              <el-input v-model="dictModel.remark" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关联用户帐号:" prop="systemType">
              <el-select v-model="dictModel.systemType" style="width: 100%" placeholder="关联用户帐号" filterable>
                <el-option
                  v-for="(item, index) in systemOptions"
                  :key="index"
                  :value="item.value"
                  :label="item.label"
                />
              </el-select>
              <!-- <el-input  v-model="dictModel.system" readonly></el-input> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用:" prop="status">
              <el-switch v-model="dictModel.status" />
              <span class="ml20">关闭后物流公司在系统停止使用</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </base-dialog>
    <!-- 审核 -->
    <base-dialog
      :visible="auditVisile"
      title="审核"
      width="640px"
      class="addDictDialog"
      @handleDialogSubmit="handleAuditSubmit"
      @handleDialogCancle="handleAuditCancle"
    >
      <el-form
        ref="auditParams"
        :model="auditParams"
        :rules="dictRule"
        label-width="120px"
        class="dictForm"
        label-position="top"
        size="medium"
      >
        <el-row :gutter="50">
          <el-col :span="24">
            <el-form-item label="审核结果:" prop="dictValue">
              <el-radio-group v-model="auditParams.resource">
                <el-radio label="通过" />
                <el-radio label="驳回" />
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审核说明:" prop="dictValue">
              <el-input v-model.trim="auditParams.dictValue" type="textarea" :rows="2" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </base-dialog>
    <!-- 完成 -->
    <base-dialog
      :visible="accomplishVisile"
      title="完成运输计划"
      width="640px"
      class="addDictDialog"
      @handleDialogSubmit="handleAccomplishSubmit"
      @handleDialogCancle="handleAccomplishCancle"
    >
      <div class="text">确定要完成计划吗</div>
      <div class="text">计划完成后，运输中的运输单不受影响，可继续执行。</div>
      <div class="text">计划量1吨，已完成1吨</div>
    </base-dialog>
    <!-- 取消 -->
    <base-dialog
      :visible="cancelVisile"
      title="取消运输计划"
      width="640px"
      class="addDictDialog"
      @handleDialogSubmit="handleCancelSubmit"
      @handleDialogCancle="handleCancelCancle"
    >
      <el-form
        ref="cancelParams"
        :model="cancelParams"
        :rules="dictRule"
        label-width="120px"
        class="dictForm"
        label-position="top"
        size="medium"
      >
        <el-row :gutter="50">
          <el-col :span="24"> 确定要取消计划吗？ </el-col>
          <el-col :span="24">
            <el-form-item label="取消说明:" prop="dictValue">
              <el-input v-model.trim="cancelParams.dictValue" type="textarea" :rows="2" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </base-dialog>
  </div>
</template>

<script>
import { validateNumber } from '@/utils/validate'
import baseDialog from '@/components/BaseDialog'
import SearchBar from '@/components/SearchBar'
import LPTablePage from '@/components/LPTablePage'
import { logininforList, delLogininfor, cleanLogininfor } from '@/api/system/logs'
import { addDateRange } from '@/utils/ruoyi'
import beiGangApi from '@/api/logistics/beigang'
// import {auditSuccess,auditReject} from "@/api/customer";

export default {
  name: 'LogisticsBill',
  components: {
    LPTablePage,
    SearchBar,
    baseDialog
  },
  data() {
    const validateNumberF = (rule, value, callback) => {
      if (Number(value) == 0) {
        return callback(new Error('不能为0'))
      }
      if (!validateNumber(value)) {
        return callback(new Error('请输入正确数字'))
      } else {
        callback()
      }
    }
    const validateEmpty = (rule, value, callback) => {
      console.log('validateEmpty', value, value instanceof Array)
      if (!(value instanceof Array)) {
        return callback(new Error('必填'))
      }
      if (value instanceof Array && value.length == 0) {
        return callback(new Error('必填'))
      } else {
        callback()
      }
    }
    return {
      auditParams: {},
      cancelParams: {},
      addVisile: false,
      auditVisile: false,
      accomplishVisile: false,
      cancelVisile: false,
      isEdit: false,
      dictModel: {
        dictValue: '',
        systemType: '',
        // items: [],
        status: '',

        remark: '',
        sysDictDataDetailList: []
      },
      searchModel: {},
      searchData: [
        {
          placeholder: '',
          prop: 'documentStatus',
          type: 'radio',

          options: [
            { label: '待派车', value: '1' },
            { label: '全部派车', value: '2' },
            { label: '已完成', value: '3' }
          ]
        },
        { prop: 'taskNumber', type: 'input', placeholder: '计划编号' },
        { prop: 'logisticsNumber', type: 'input', placeholder: '物流单号' },
        { prop: 'transportNumber', type: 'input', placeholder: '运输单号' },
        {
          prop: 'logisticsCompany',
          type: 'select',
          placeholder: '物流公司',
          options: []
        },
        {
          prop: 'supplier',
          type: 'select',
          placeholder: '供应商',
          options: []
        },
        {
          prop: 'startPoint',
          type: 'select',
          placeholder: '起点',
          options: [
            { label: '来源1', value: '0' },
            { label: '来源2', value: '1' }
          ]
        },
        {
          prop: 'endPoint',
          type: 'select',
          placeholder: '终点',
          options: [
            { label: '来源1', value: '0' },
            { label: '来源2', value: '1' }
          ]
        },
        { placeholder: '物料描述', prop: 'materialDescription', type: 'input' },
        { placeholder: '物料编码', prop: 'materialCode', type: 'input' },
        {
          label: '创建时间',
          prop: 'createdTime',
          type: 'datetimerange',
          startPlaceholder: '起始时间',
          endPlaceholder: '结束时间',
          span: 6
        },
        {
          prop: 'search',
          type: 'button',
          policy: ['system.log.query']
        }
      ],
      tableData: [],
      tableColumn: [
        { label: '物流单号', prop: 'logisticsNumber', fixed: 'left', width: 200, render: true },
        { label: '物流公司', prop: 'logisticsCompany', width: 150 },
        { label: '单据状态', prop: 'documentStatus', width: 150, render: true },
        { label: '计划量(吨)', prop: 'plannedQuantity', sortable: true, width: 150 },
        { label: '已完成量(吨)', prop: 'completedQuantity', sortable: true, width: 150 },
        { label: '未完成量(吨)', prop: 'remainingQuantity', sortable: true, width: 150 },
        { label: '需求车数(辆)', prop: 'requiredTrucks', sortable: true, width: 150 },
        { label: '物料描述', prop: 'materialDescription', width: 150 },
        { label: '起点', prop: 'startPoint', width: 150 },
        { label: '终点', prop: 'endPoint', width: 150 },
        { label: '船名', prop: 'shipName', width: 150 },
        { label: '进厂时间', prop: 'entryTime', width: 150 },
        { label: '车型', prop: 'vehicleType', width: 150 },
        { label: '运输计划编号', prop: 'taskNumber', sortable: true, width: 150, render: true },
        { label: '供应商', prop: 'supplier', width: 150 },
        { label: '操作时间', prop: 'operationTime', sortable: true, width: 150 },
        { label: '操作人', prop: 'operator', width: 150 },
        { label: '创建时间', prop: 'createdTime', sortable: true, width: 150 },
        { label: '创建人', prop: 'createdBy', width: 150 },
        { label: '创建来源', prop: 'creationSource', width: 150 },
        {
          label: '操作',
          prop: 'action',
          fixed: 'right',
          type: 'button',
          width: 120,
          buttons: [
            {
              label: '查看',
              type: 'text',
              color: 'rgba(0, 118, 255, 1)',
              method: 'handleDetail'
            }
          ]
        }

        //  {
        //     label: "操作",
        //     prop: "action",
        //     type: "button",
        //     hideTooLtip:true,
        //     width:180,
        //     button:[
        //         {
        //             label: "查看",
        //             type: "text",
        //             icon: "el-icon-view",
        //             method:`_detail${this.$options.name}`
        //         },
        //         {
        //             label: "通过",
        //             type: "text",
        //             icon: "el-icon-view",
        //             hide:'isCanTakeAudit',
        //             // hide:'canTakeAudit',
        //             hideValue:[false],
        //             policy:['Crm.CluePoolManage.TakeAudit'],
        //             method:`_auditSuccess${this.$options.name}`
        //         },
        //         {
        //             label: "驳回",
        //             type: "text",
        //             icon: "el-icon-view",
        //             hide:'isCanTakeAudit',
        //             // hide:'canTakeAudit',
        //             hideValue:[false],
        //             policy:['Crm.CluePoolManage.TakeAudit'],
        //             method:`_auditFail${this.$options.name}`
        //         },
        //     ]
        //  }
      ],
      total: 0,
      currentPage: 1,
      selectArr: [],
      allotVisile: false,
      allotModel: {},
      allotRule: {
        responsibleUserId: [
          // { required: true, trigger: "blur", message: "必填" },
          { validator: validateEmpty, required: true, trigger: 'blur' }
        ]
      },
      userOptions: [],
      settingVisile: false,
      ruleModel: {},
      ruleRule: {
        autoRecycleEnable: [{ required: true, trigger: 'blur', message: '必填' }],
        autoRecycleByNotFollowUpOverDays: [
          { required: true, trigger: 'blur', message: '必填' },
          { validator: validateNumberF, required: true, trigger: 'blur' }
        ],

        originalResponsibleUserTakeLimit: [{ required: true, trigger: 'blur', message: '必填' }],
        originalResponsibleUserTakeLimitDays: [
          { required: true, trigger: 'blur', message: '必填' },
          { validator: validateNumberF, required: true, trigger: 'blur' }
        ],
        takeLimit: [{ required: true, trigger: 'blur', message: '必填' }],
        takeLimitByEveryDayNumbers: [
          { required: true, trigger: 'blur', message: '必填' },
          { validator: validateNumberF, required: true, trigger: 'blur' }
        ]
      },
      detailVisible: false,
      detailId: '',
      openSeaClueId: '',
      status: null,
      isCanTakeAudit: null
    }
  },
  mounted() {
    this.getLogininforList()
    // 详情
    this.$bus.$on('handleDetail', (rows) => {
      this.$router.push({ path: `/logistics/beiGang/logisticsBillDetail/${rows.id}` })
    })
    // 编辑
    this.$bus.$on('handleEdit', (rows) => {
      this.$router.push({ path: `/logistics/beiGang/transportUpdate/${rows.id}` })
    })
    // 审核
    this.$bus.$on('handleAudit', (rows) => {
      this.auditVisile = true
      // this.$router.push({ path: `/system/msg/edit/${rows.id}` })
    })
    // 完成
    this.$bus.$on('handleAccomplish', (rows) => {
      this.accomplishVisile = true
    })
    // 取消
    this.$bus.$on('handleCancel', (rows) => {
      this.cancelVisile = true
    })
    // 删除
    this.$bus.$on('handleDelete', (rows) => {
      this.$confirm('确定删除吗', '取消', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        closeOnClickModal: false
      }).then(() => {
        //   console.log('确认');
        deleteFollow({ id: row.id }).then((res) => {
          if (!res.error) {
            this.$message.success('删除成功')
            this.getFollowList()
          }
        })
      })
    })
  },
  destroyed() {
    this.$bus.$off('handleDetail')
    this.$bus.$off('handleDelete')
    this.$bus.$off('handleEdit')
    this.$bus.$off('handleAudit')
    this.$bus.$off('handleAccomplish')
    this.$bus.$off('handleCancel')
  },
  methods: {
    navigateToDetail(id, type) {
      if (type === 'taskNumber') {
        this.$router.push({ path: `/logistics/beiGang/transportDetail/${id}` })
      } else if (type === 'logisticsNumber') {
        this.$router.push({ path: `/logistics/beiGang/logisticsBillDetail/${id}` })
      }
    },
    // 批量操作
    handleCommand(command) {
      //   if (command == "import") {
      //     this.importVisible = true;
      //     console.log("批量导入");
      //   } else if (command == "export") {
      //     this.exportData();
      //     console.log("批量导入");
      //   }
      switch (command) {
        case 'audit':
          break
        // 启用
        case 'import':
          break
        // 禁用
        case 'export':
          break
        // 删除
        default:
          break
      }
    },
    // 新增
    add() {
      this.$router.push({ path: 'logistics/beiGang/transportInsert' })
    },
    handleAddSubmit() {
      this.$refs.dictForm.validate((valid) => {
        if (valid) {
          console.log('handleAddSubmit 验证通过', this.dictModel)
          if (!this.isEdit) {
            addDict(this.dictModel).then((res) => {
              if (!res.error) {
                console.log('addDict', res)
                this.dictModel = {
                  items: []
                }
                this.$message.success('添加字典成功')
                this.addVisile = false
                this.getDictList()
              }
            })
          } else {
            editDict(this.dictModel).then((res) => {
              if (!res.error) {
                console.log('editDict', res)
                this.dictModel = {
                  items: []
                }
                this.$message.success('编辑字典成功')
                this.addVisile = false
                this.getDictList()
              }
            })
          }
        } else {
          this.$message.warning('请检查字典信息')
          return false
        }
      })
    },
    handleAddCancle() {
      this.dictModel = this.$options.data().dictModel
      this.resetForm('dictForm')
      this.addVisile = false
    },
    // 审核操作
    handleAuditSubmit() {},
    handleAuditCancle() {
      this.auditParams = this.$options.data().auditParams
      this.resetForm('auditParams')
      this.auditVisile = false
    },
    // 完成操作
    handleAccomplishSubmit() {},
    handleAccomplishCancle() {
      this.accomplishVisile = false
    },
    // 取消操作
    handleCancelSubmit() {},
    handleCancelCancle() {
      this.cancelParams = this.$options.data().cancelParams
      this.resetForm('cancelParams')
      this.cancelVisile = false
    },
    getLogininforList() {
      // addDateRange

      const { pageSize } = this.$refs.tablePage
      const params = {
        ...this.searchModel,
        pageSize: pageSize,
        pageNum: this.currentPage
      }
      const obj = addDateRange(params, this.searchModel.loginTime)
      delete obj.loginTime

      beiGangApi.logisticsBillList(obj).then((res) => {
        if (!res.error) {
          this.total = res.total
          this.tableData = res.rows
        }
      })
      // 获取参与物流公司
      beiGangApi.logisticsCompanyoList().then((res) => {
        if (!res.error) {
          const enabledCompanies = res.rows
            .filter((company) => company.isEnabled === 1)
            .map((company) => ({
              label: company.companyName,
              value: company.id
            }))
          // 更新参与物流公司的 options
          this.searchData.find((item) => item.prop === 'logisticsCompany').options = enabledCompanies
        }
      })
      // 获取供应商
      beiGangApi.supplierList().then((res) => {
        if (res.code == 200) {
          // 使用 ksqc 字段作为 label
          const supplier = res.data.map((supplier) => ({
            label: supplier.ksqc, // 使用 ksqc 作为 label
            value: supplier.srmgysbm // 假设供应商编码是唯一标识符，作为 value
          }))
          // 填充到供应商的 options
          this.searchData.find((item) => item.prop === 'supplier').options = supplier
        }
      })
      // 获取起点
      beiGangApi.getByType({ useTo: '起点' }).then((res) => {
        if (res.code === 200) {
          // 将顶层属性名“仓库”作为一级选项，内部对象作为二级选项
          const startPointOptions = Object.keys(res.data).map((key) => ({
            label: key, // 一级选项标签，值为“仓库”等顶级属性名
            value: key,
            children: res.data[key].map((item) => ({
              label: item.name, // 二级选项标签，值为具体仓库/港口的名称
              value: item.locationId, // 二级选项值
              children: item.nestedData
                ? item.nestedData.map((nestedItem) => ({
                    label: nestedItem.name, // 三级选项标签
                    value: nestedItem.id // 三级选项值
                  }))
                : null
            }))
          }))
          // 将选项赋值给对应的 searchData
          this.searchData.find((item) => item.prop === 'startPoint').options = startPointOptions
        }
      })
      // 获取终点
      beiGangApi.getByType({ useTo: '终点' }).then((res) => {
        if (res.code === 200) {
          // 构造终点选项结构，类似起点
          const endPointOptions = Object.keys(res.data).map((key) => ({
            label: key,
            value: key,
            children: res.data[key].map((item) => ({
              label: item.name,
              value: item.locationId,
              children: item.nestedData
                ? item.nestedData.map((nestedItem) => ({
                    label: nestedItem.name,
                    value: nestedItem.id
                  }))
                : null
            }))
          }))
          // 将选项赋值给对应的 searchData
          this.searchData.find((item) => item.prop === 'endPoint').options = endPointOptions
        }
      })
    },
    selectable(row, index) {
      // if (row.status == 0) {
      //   return true
      // } else {
      //   return false
      // }
      return true
    },

    handleSearchSubmit() {
      this.currentPage = 1
      this.getLogininforList()
    },
    handleSearchReset() {
      this.currentPage = 1
      this.$refs.tablePage.clearSelection()
      this.getLogininforList()
    },
    handleSizeChange(v) {
      this.pageSize = v
      this.currentPage = 1
      this.getLogininforList()
    },
    handleCurrentChange(v) {
      this.currentPage = v
      this.getLogininforList()
    },
    handleSelectionChange(v) {
      console.log('handleSelectionChange', v)
      this.selectArr = v
    },
    allot() {
      this.$modal
        .confirm('是否确认清空所有登录日志数据项？')
        .then(function () {
          return cleanLogininfor()
        })
        .then(() => {
          this.getLogininforList()
          this.$modal.msgSuccess('清空成功')
        })
        .catch(() => {})
    },

    deleteCustomer() {
      if (this.selectArr.length == 0) {
        this.$message.warning('请先勾选日志')
        return
      }
      this.$confirm('确定删除吗', '删除', {
        cancelButtonText: '取消',
        confirmButtonText: '确定',
        closeOnClickModal: false
      }).then(() => {
        //   console.log('确认');
        const params = {
          ids: this.selectArr.map((item) => item.infoId)
        }
        delLogininfor(params.ids).then((res) => {
          if (!res.error) {
            this.$message.success('操作成功')
            this.getLogininforList()
            this.$refs.tablePage.clearSelection()
          }
        })
      })
    },
    gethtml(value) {
      if (value == null) {
        return
      }
      var list = value.split(',')
      var resultStr = ''
      list.forEach((item) => {
        if (item.includes('高') || item.includes('重要')) {
          resultStr = resultStr + "<span style='color:#EE3333'>" + item + '</span>,'
        } else {
          resultStr = resultStr + item + ','
        }
      })
      if (resultStr != '') {
        return resultStr.slice(0, -1)
      }
    },
    showSettign() {
      getOpenSeaSetting().then((res) => {
        if (!res.error) {
          console.log('getOpenSeaSetting', res)
          this.ruleModel = res
          this.settingVisile = true
        }
      })
    },
    handleSettingSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          console.log('ruleModel', this.ruleModel)
          putOpenSeaStting(this.ruleModel).then((res) => {
            if (!res.error) {
              this.$message.success('保存设置成功')
              this.settingVisile = false
            }
          })
        } else {
          return false
        }
      })
    },
    handleSettingCancle() {
      this.settingVisile = false
    },
    detailClose() {
      this.detailVisible = false
      this.getLogininforList()
    },
    handleAllot() {
      this.allotVisile = true
    },

    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.logisticsBill_block {
  // padding: 0 .2rem .2rem;
  .top {
    background-color: #fff;
    padding: 0 0.3rem;
  }

  .bottom {
    .btn_area {
      margin-bottom: 0.2rem;
      margin-left: 0.2rem;
    }

    background-color: #fff;
    margin-top: 0.2rem;
    padding: 0.2rem 0rem;
  }
}
.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 5px;
}
.orange {
  background-color: orange;
}
.blue {
  background-color: rgb(0, 123, 255);
}

.green {
  background-color: green;
}

.gray {
  background-color: gray;
}

.red {
  background-color: red;
}
// ::v-deep .el-table__body-wrapper {
//   position: relative;
//   left: 355px;
// }
</style>
